//
//  MagazineShelfViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-6-3.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "MagazineShelfViewController.h"
#import "NovelCell.h"
#import "DataBase.h"
#import "ASIDownloadCache.h"
#import "MagazineInfoViewController.h"
#import "AppDelegate.h"
@interface MagazineShelfViewController ()

@end

@implementation MagazineShelfViewController
- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:lastReadView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)backBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)lastRead:(id)sender {
    if (![[AuthorManager defaultManager] hasLoggedIn]) {
//        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"请先登录"] autorelease];
//        [abp show];
    }else{
        [self getData];
    }
    lastRead.selected = YES;
    downloaded.selected = NO;
    lastReadView.hidden = NO;
    downloadedView.hidden = YES;

}
- (IBAction)downloaded:(id)sender {
//    downloaded.selected = YES;
//    lastRead.selected = NO;
//    lastReadView.hidden = YES;
//    downloadedView.hidden = NO;
//    NSArray * array = [[DataBase shareDB] selectMagaInfo];
//    [downloadArray removeAllObjects];
//    for (NSDictionary * dict in array) {
//        ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:ArticleInfoURL,[AuthorManager defaultManager].userID,[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
////        NSLog(@"request :%@",request.url.absoluteString);
//        if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
//            [downloadArray addObject:dict];
//        }else{
//            ASIHTTPRequest * request1 = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:ArticleInfoURL,@"",[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
//            if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request1]){
//                [downloadArray addObject:dict];
//            }
//        }
//    }
//    if (downloadArray && downloadArray.count != 0) {
//        [downloadedView reloadData];
//    }else{
//        downloadedView.hidden = YES;
//        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"还没有下载任何杂志"]autorelease];
//        [abp show];
//    }


}

-(NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView{
    if (gridView == lastReadView) {
        return mDataArray.count;
    }
    return downloadArray.count;
}
-(AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index{
    if (gridView == lastReadView) {
        static NSString * cellID = @"cellID";
        NovelCell * cell = (NovelCell *)[gridView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[NovelCell alloc]initWithFrame:CGRectMake(0, 0, 70, 100) reuseIdentifier:cellID];
        }
        cell.novelInfo = [mDataArray objectAtIndex:index];
        [cell updateDisplayWithImageStr:@"image"];
        
        return cell;

    }else{
        static NSString *CellIdentify = @"cellID";
        NovelCell * cell = (NovelCell *)[gridView dequeueReusableCellWithIdentifier:CellIdentify];
        if (cell == nil) {
            cell = [[NovelCell alloc]initWithFrame:CGRectMake(0, 0, 70, 100) reuseIdentifier:CellIdentify];
        }
        cell.novelInfo = [downloadArray objectAtIndex:index];
        
        [cell updateDisplayWithImageStr:@"cover_image"];
        
        return cell;

    }
}
-(CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView{
    return CGSizeMake(80, 150);
}
- (CGRect)gridView:(AQGridView *)gridView adjustCellFrame:(CGRect)cellFrame withinGridCellFrame:(CGRect)gridCellFrame
{
    cellFrame.origin.y -= 5;
    return cellFrame;
}
-(void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index{
    MagazineInfoViewController * magazineInfoViewController = [[MagazineInfoViewController alloc]initWithNibName:@"MagazineInfoViewController" bundle:nil];
    if (gridView == lastReadView) {
        magazineInfoViewController.basicInfo = [mDataArray objectAtIndex:index];
    }else{
        magazineInfoViewController.basicInfo = [downloadArray objectAtIndex:index];
    }
    [[UIApplication rootNavController] pushViewController:magazineInfoViewController animated:YES];
    [gridView deselectItemAtIndex:index animated:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    shouldSwipeBack = YES;
    // Do any additional setup after loading the view from its nib.
    downloadArray = [[NSMutableArray alloc]initWithCapacity:0];
    UIView *bgView1 = [[UIView alloc] init];
    bgView1.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bookshelf_cell_bg"]];
    
    downloadedView.backgroundView = bgView1;
    downloadedView.backgroundViewExtendsDown = YES;
    downloadedView.leftContentInset = 20;
    downloadedView.rightContentInset = 20;
    downloadedView.contentInset = UIEdgeInsetsMake(0, 0, 1, 0);

    
    
//    if (![[AuthorManager defaultManager] hasLoggedIn]) {
//        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"请先登录"] autorelease];
//        [abp show];
//    }else{
//        UIView *bgView = [[UIView alloc] init];
//        bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bookshelf_cell_bg"]];
//        lastReadView.backgroundView = bgView;
//        lastReadView.backgroundViewExtendsDown = YES;
//        lastReadView.leftContentInset = 20;
//        lastReadView.rightContentInset = 20;
//        lastReadView.contentInset = UIEdgeInsetsMake(0, 0, 1, 0);
//        mDataArray = [[NSMutableArray alloc]initWithCapacity:0];
//    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (lastRead.selected) {
        if ([[AuthorManager defaultManager] hasLoggedIn]) {
            [self getData];
        }
    }else{
        
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSArray * array = [[DataBase shareDB] selectMagaInfo];
    [downloadArray removeAllObjects];
    for (NSDictionary * dict in array) {
        ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:ArticleInfoURL,[AuthorManager defaultManager].userID,[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        //        NSLog(@"request :%@",request.url.absoluteString);
        if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
            [downloadArray addObject:dict];
        }else{
            ASIHTTPRequest * request1 = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:ArticleInfoURL,@"",[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
            if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request1]){
                [downloadArray addObject:dict];
            }
        }
    }
    if (downloadArray && downloadArray.count != 0) {
        downloadedView.hidden = NO;
        reLabel.hidden = YES;
        [downloadedView reloadData];
    }else{
        reLabel.hidden = NO;
        downloadedView.hidden = YES;
    }
}

-(void)getData{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] getRecentReaded];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            if ([obj isKindOfClass:[NSDictionary class]] && obj != nil) {
                [mDataArray removeAllObjects];
                [mDataArray addObjectsFromArray:[obj objectForKey:@"result"]];
                [lastReadView reloadData];
            }
        });
    });
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [mDataArray release];
    [lastRead release];
    [downloaded release];
    [lastReadView release];
    [downloadedView release];
    [reLabel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [lastRead release];
    lastRead = nil;
    [downloaded release];
    downloaded = nil;
    [lastReadView release];
    lastReadView = nil;
    [downloadedView release];
    downloadedView = nil;
    [super viewDidUnload];
}
@end
